package report

import (
	"encoding/json"
	"github.com/zeebo/errs"
	"go.uber.org/zap"
	"net"
)

var Error = errs.Class("Report")

type Config struct {
	Endpoint string `help:"上报地址" default:""`
}

type Reporter struct {
	log  *zap.Logger
	conn *net.UDPConn
}

func NewReporter(conf *Config) *Reporter {
	if conf.Endpoint == "" {
		return &Reporter{}
	}
	udpAddr, _ := net.ResolveUDPAddr("udp", conf.Endpoint)
	conn, err := net.DialUDP("udp", nil, udpAddr)
	if err != nil {
		return nil
	}
	return &Reporter{
		conn: conn,
	}
}

func (r *Reporter) send(data any) {
	if r.conn == nil {
		return
	}
	res, err := json.Marshal(data)
	if err != nil {
		r.log.Error("json marshal err", zap.Error(err))
	}
	n, err := r.conn.Write(res)
	if err != nil {
		r.log.Error("send stat err", zap.Error(err))
	}
	if n != len(res) {
		r.log.Error("send data incomplete")
	}
}
